package example.borrow;


import example.entity.Borrow;
import example.entity.Fine;
import example.service.BorrowService;
import example.service.FineService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@WebServlet("/updateBorrowServlet")
public class UpdateBorrowServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        int borrowId = Integer.parseInt(request.getParameter("borrowId"));
        try {
            //计算归还日期有没有超过规定归还日期
            Borrow borrow = BorrowService.getBorrowById(borrowId);
            if (borrow.getDueDate().before(new Date())) {
                //计算超过多少天 1天10块
                int days = (int) ((new Date().getTime() - borrow.getDueDate().getTime()) / (1000 * 3600 * 24));

                //判断是否已经有罚款记录，没有就加记录，有就更新罚款
                Fine finesByBorrowId = FineService.getFinesByBorrowId(borrowId);
                if (finesByBorrowId != null) {
                    FineService.payAmount(10 * days, finesByBorrowId.getFineId());
                } else {
                    FineService.addFine(borrow.getUserId(), borrow.getBookId(), 10 * days, borrowId);
                }

                response.getWriter().println("归还日期已过规定日期，请先缴纳罚款再归还书籍");
                response.sendRedirect("fineServlet");
            } else {
                Borrow record = new Borrow();
                record.setBorrowId(borrowId);
                record.setReturnDate(new Date());

                BorrowService.updateBorrow(record);

                response.sendRedirect("listBorrowsServlet");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 可以根据实际情况给前端返回更友好的错误提示，比如设置错误信息到请求属性，转发到错误页面等
        }
    }
}
